package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.config.EmailConfig;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.dto.UserVerifyRequest;
import com.mall.user.dto.UserVerifyResponse;
import com.mall.user.mq.delay.RegisterSendEmailProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Jcy
 */
@Service
@Slf4j
@EnableConfigurationProperties(EmailConfig.class)
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private EmailConfig emailConfig;

    @Autowired
    private RegisterSendEmailProducer producer;

    /**
     * 注册
     *
     * @param request
     * @return
     */
    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        UserRegisterResponse response = new UserRegisterResponse();
        try {
            //判空，以及邮箱格式
            request.requestCheck();
            //判断用户名，邮箱是否已存在
            isRepeat(request);
        } catch (ValidateException e) {
            response.setCode(e.getErrorCode());
            response.setMsg(e.getMessage());
            return response;
        }
        //用户表插入用户信息
        Member member = new Member();
        member.setUsername(request.getUserName());
        //密码加密
        String pwd = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
        member.setPassword(pwd);
        member.setEmail(request.getEmail());
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setState(1);//默认值
        int affectRows = memberMapper.insertSelective(member);
        if (affectRows != 1) {
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }

        //用户验证表插入信息
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(request.getUserName());
        userVerify.setRegisterDate(new Date());
        String key = request.getUserName() + request.getEmail() + UUID.randomUUID().toString();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        int rows = userVerifyMapper.insertSelective(userVerify);
        if (rows != 1) {
            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return response;
        }

        try {
            //通过mq发送邮件激活
            boolean sendEmail = sendEmail(uuid, request);
            if (!sendEmail){
                response.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
                response.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
                return response;
            }
        } catch (Exception e) {
            response.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
            response.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
            return response;
        }

        //打印日志
        log.info("用户注册成功：{}", JSON.toJSONString(request));

        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    /**
     * 激活
     *
     * @param request
     * @return
     */
    @Override
    public UserVerifyResponse verify(UserVerifyRequest request) {
        UserVerifyResponse response = new UserVerifyResponse();
        try {
            //判空
            request.requestCheck();
            //修改verify的is_verify为Y
            Example exampleUserVerify = new Example(UserVerify.class);
            exampleUserVerify.createCriteria().andEqualTo("uuid", request.getUuid());
            UserVerify userVerify = new UserVerify();
            userVerify.setIsVerify("Y");
            userVerifyMapper.updateByExampleSelective(userVerify, exampleUserVerify);
            //修改member的is_verify为Y
            Example exampleMember = new Example(Member.class);
            exampleMember.createCriteria().andEqualTo("username", request.getUserName());
            Member member = new Member();
            member.setIsVerified("Y");
            member.setUpdated(new Date());
            memberMapper.updateByExampleSelective(member, exampleMember);
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            response.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            response.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
        }
        return response;
    }

    /**
     * 发送激活邮件
     *
     * @param request
     * @param uuid
     */
    private boolean sendEmail(String uuid, UserRegisterRequest request) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailConfig.getFrom());
        message.setTo(request.getEmail());
        message.setSubject(emailConfig.getSubject());
        message.setText(emailConfig.getUrl() + "?uid=" + uuid + "&username=" + request.getUserName());
//        javaMailSender.send(message);
        //调用mq生产者方法发送消息
        return producer.sendRegisterEmailMessage(message);
    }

    /**
     * 判断用户名和邮箱是否已存在
     *
     * @param request
     */
    private void isRepeat(UserRegisterRequest request) {
        //用户名重复
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(), SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
        //邮箱重复
        Example exampleEmail = new Example(Member.class);
        exampleEmail.createCriteria().andEqualTo("email", request.getEmail());
        List<Member> membersEmail = memberMapper.selectByExample(exampleEmail);
        if (!CollectionUtils.isEmpty(membersEmail)) {
            throw new ValidateException(SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getCode(), SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getMessage());
        }
    }
}
